//index.js
//获取应用实例
const app = getApp()
var amapFile = require('../../utils/amap-wx.js');
var md5 = require('../../utils/md5.js');
const util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    jnHeight: 0,
    jnTop: 0,
    scrollTop: 0,
    current: 0,
    dialogShow: false,
    popshow: false, //弹窗
    libraryList: [], //图书馆列表
    currentLibraryIndex: 0,
    currentLibraryId: null,
    isOver: true,
    currentSite: null,
    province: '',
    city: '',
    district: '',
    latitude: '',
    longitude: '',
    pageNumber: 1,
    listType: 'local',
    locationShow: true,
    banner1: [],
    banner2: [],
    startTime: '',
    endTime: '',
    top: 0,
    scanoffset: 0,
    newBanner: [{
        id: 1,
        name: "本馆概况",
        coverUrl: "https://wxgt.chaoxing.com/static/images/ningxia/bggk_icon.png",
        detailUrl: encodeURIComponent("https://thyt.chaoxing.com/mobile/appointment/list?nodeId=1309")
      },
      {
        id: 2,
        name: "线上预约",
        coverUrl: "https://wxgt.chaoxing.com/static/images/ningxia/xsyy_icon.png",
        detailUrl: encodeURIComponent("https://thyt.chaoxing.com/mobile/pavilion/list?nodeId=1311")
      },
      {
        id: 3,
        name: "文创小店",
        coverUrl: "https://wxgt.chaoxing.com/static/images/ningxia/wcxd_icon.png",
        detailUrl: encodeURIComponent("https://thyt.chaoxing.com/mobile/information/list?nodeId=1308")
      },
      {
        id: 4,
        name: "名师讲坛",
        coverUrl: "https://wxgt.chaoxing.com/static/images/ningxia/msjt_icon.png",
        detailUrl: encodeURIComponent("https://bdfw.superlib.com/gbrec/html/index.html?mid=1")
      },
    ],
    zjyyStatus: false,
    zjyyList: [],
    newsTabIndex: 0,
  },

  zjyy: function (defaultFid) {
    var that = this;
    var encarr = [{
      wfwfid: app.globalData.fid
    }, {
      pageSize: 2
    }, {
      defaultFid: defaultFid
    }]
    var enc = app.generateEnc(encarr)
    wx.request({
      url: app.url.wxgtBaseUrl+'wechat/news/cateResource',
      data: {
        wfwfid: app.globalData.fid,
        pageSize: 2,
        defaultFid: defaultFid,
        enc: enc
      },
      success: function (data) {
        if (data.data.code == 200 && data.data.data.length > 0) {
          that.setData({
            zjyyStatus: true,
            zjyyList: data.data.data
          })
        } else {
          that.setData({
            zjyyStatus: false,
            zjyyList: []
          })
        }
      }
    })
  },
  // 新闻切换
  changeNewsTab: function (e) {
    console.log(e.currentTarget.dataset.index);
    this.setData({
      newsTabIndex: e.currentTarget.dataset.index
    })
  },
  /**
   * 点击新闻跳转逻辑
   */
  navigatorNews: function (e) {
    console.log(e);
    if (e.currentTarget.dataset.type == 0) {
      console.log(12345678)
      wx.navigateTo({
        url: '/pages/newsInfo/newsInfo?infoid=' + e.currentTarget.dataset.infoid + '&appid=' + e.currentTarget.dataset.appid,
      })
    } else if (e.currentTarget.dataset.type == 1) {
      console.log(99999999)

      wx.navigateTo({
        url: '/pages/link/link?url=' + encodeURIComponent(e.currentTarget.dataset.content),
      })
    } else {
      wx.navigateTo({
        url: e.currentTarget.dataset.content
      })
    }
  },

  slidehandle: function (e) {
    // console.log(e.detail.current);
    this.setData({
      current: e.detail.current
    })
  },

  scancode: function () {
    console.log(11)
  },


  toyydlHandle: function () {
    console.log("-----------")
    console.log(wx.getStorageSync('token'), wx.getStorageSync('hasLogin'))
    // /pages/yyindex/yyindex;
    var phoneNumber = wx.getStorageSync('token')
    if (phoneNumber) {
      wx.navigateTo({
        url: '/pages/yyindex/yyindex',
      })
    } else if (!wx.getStorageSync('hasLogin')) {
      // wx.setStorageSync('hasLogin', false);
      // wx.setStorageSync('permission', false);
      wx.switchTab({
        url: '/pages/mime/mime',
      })
    } else {
      this.selectComponent('#vanpopup').getpopupstate()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var obj = wx.getMenuButtonBoundingClientRect()
    this.setData({
      jnHeight: obj.height + obj.top,
      scanoffset: obj.top + 5
    })
    console.log(options, options.scene);
    const scene = options.scene
    console.log(11111, scene)
    console.log(scene !== 'undefined')
    // 当从二维码进入时，跳转相关页面
    if (scene && scene !== 'undefined') {
      wx.navigateTo({
        url: `/pages/exhibition/detail/detail?id=${scene}`
      });
    }
    // 选择单位弹窗


    let vm = this;
    console.log(app.globalData.allowLocation + " -- " + app.globalData.passEnc + " -- " + app.globalData.fid + " -- " + app.globalData.fidEnc);
    var cxid = wx.getStorageSync('cxid');
    var fid = wx.getStorageSync('fid');
    var site = wx.getStorageSync('site');
    var new_fid = options.fid == undefined ? app.globalData.fid : options.fid;
    var new_enc = options.fidEnc == undefined ? app.globalData.fidEnc : options.fidEnc;
    if (cxid && cxid > 0 && fid && fid > 0) {
      app.globalData.fid = fid;
      app.globalData.site = site;
      // 2020-09-10
      // vm.checkFidEnc(fid);
      vm.checkFidEnc(app.globalData.fid);
      console.log("我在这")
    } else {
      if (app.globalData.allowLocation == false) {
        vm.checkFidEnc(app.globalData.fid);
        // vm.getUserLocation();
      } else if (app.globalData.allowLocation == true && app.globalData.passEnc == true) {
        vm.checkFidEnc(app.globalData.fid)
      } else {
        vm.checkFidEnc(app.globalData.fid)
      }
    }

    this.getBanner(1)
    this.getBanner(2)
    this.getBanner(3)
    this.zjyy()
  },


  /**
   * 获取小banner的列表
   */
  getBanner: function (type) {
    var that = this;
    var encarr = [{
      fid: app.globalData.fid
    }, {
      pageSize: 30
    }, {
      pageNumber: 1
    }, {
      type: type
    }, {
      defaultFid: 117890
    }]
    var enc = app.generateEnc(encarr)
    wx.request({
      url: app.url.manageshequ3BaseUrl+'api/banner',
      data: {
        fid: app.globalData.fid,
        type: type,
        pageSize: 30,
        pageNumber: 1,
        defaultFid: 117890, //数据为空的话，使用这个fid下的默认资源 add by carlos at 2020-05-20
        libraryType: 3, //类型 1图书馆 add by carlos at 2020-05-20
        sid: 1, //预留字段 add by carlos at 2020-05-20
        enc: enc
      },
      success: function (res) {
        if (type == 1) {
          that.setData({
            banner1: []
          })
        } else if (type == 2) {
          that.setData({
            banner2: []
          })
        } else if (type == 3) {
          that.setData({
            banner3: []
          })
        }
        if (res.data.code == 200) {
          if (type == 1) {
            that.setData({
              banner1: that.data.banner1.concat(res.data.data.records)
            })
          } else if (type == 2) {
            that.setData({
              banner2: that.data.banner2.concat(res.data.data.records),
              startTime: res.data.data.records[1].title.split('-')[0],
              endTime: res.data.data.records[1].title.split('-')[1]
            })
          } else if (type == 3) {
            that.setData({
              banner3: that.data.banner3.concat(res.data.data.records),
            })
          }

        } else {
          console.log("获取banner接口异常");
        }
      },
      fail: function () {
        console.log("请求banner失败");
      }
    })
  },


  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop
    })
  },

  tolinkhandle: function (e) {
    console.log(e.currentTarget.dataset)
    var url = encodeURIComponent(e.currentTarget.dataset.url);
    var name = e.currentTarget.dataset.name;
    var index = Number(e.currentTarget.dataset.index)
    // wx.navigateTo({
    //   url: '/pages/link/link?url=' + url + '&name=' + name
    // })

    var that = this;
    var banner = null;
    if (e.currentTarget.dataset.type == 1) {
      banner = that.data.banner1[index];
    } else if (e.currentTarget.dataset.type == 2) {
      banner = that.data.banner2[index];
    } else if (e.currentTarget.dataset.type == 3) {
      banner = that.data.banner3[index];
    }
    var finalUrl = banner.linkUrl;
    console.log(finalUrl, '...finalUrl1')

    var paras = banner.parameters;
    // var finalUrl = url;
    // var paras = e.currentTarget.dataset.parameters;
    var cxid = wx.getStorageSync('cxid');
    //判断是否需要登录
    if (banner.needLogin == 1) {
      //需要登录的模块
      if (cxid && cxid > 0) {
        //已登录的状态 判断需要携带的参数
        if (paras != null && paras.length > 0) {
          //有参数 需要拼接参数  完成后页面跳转
          if (finalUrl.startsWith('/pages/')) {
            //需要拼接参数 小程序内部页面不要传额外参数
            console.log("有参数 小程序内跳转 " + finalUrl);
            wx.navigateTo({
              url: finalUrl,
            })
          } else {
            finalUrl = banner.linkUrl.replace("?", "&");
            //需要拼接参数 参数名称需要是固定的，比如uid fid dxfid
            var parasList = paras.split(",");
            for (var i = 0; i < parasList.length; i++) {
              if (parasList[i] == "uid") {
                finalUrl = finalUrl + "&" + parasList[i] + "=" + cxid;
              } else if (parasList[i] == "fid") {
                finalUrl = finalUrl + "&" + parasList[i] + "=" + app.globalData.fid;
              } else if (parasList[i] == "dxfid") {
                finalUrl = finalUrl + "&" + parasList[i] + "=" + app.globalData.site.schoolid;
              } else if (parasList[i] == "enc") {
                //入馆预约定制
                var md5str = '[fid=' + app.globalData.fid + '][uid=' + wx.getStorageSync('cxid') + '][)lEeoJVv0Y7T5e*=SC]';
                var _enc = md5.md5(md5str);
                finalUrl = finalUrl + "&" + parasList[i] + "=" + _enc;
              }
            }
            console.log("有参数跳转 " + finalUrl);
            wx.navigateTo({
              url: '/pages/link/link?url=' + finalUrl + '&name=' + name,
            })
          }

        } else {
          //没有额外参数 直接跳转  需要判断是内嵌还是小程序私有页面
          if (finalUrl.startsWith('/pages/')) {
            console.log("无参数 小程序内跳转 " + finalUrl);
            wx.navigateTo({
              url: finalUrl,
            })
          } else {
            if (finalUrl.indexOf("?") > -1) {
              finalUrl = finalUrl + "&uid=" + cxid + "&fid=" + app.globalData.fid + "&dxfid=" + app.globalData.site.schoolid;
            } else {
              finalUrl = finalUrl + "?uid=" + cxid + "&fid=" + app.globalData.fid + "&dxfid=" + app.globalData.site.schoolid;
            }
            wx.navigateTo({
              url: '/pages/link/link?url=' + encodeURIComponent(finalUrl + '&name=' + name),
            })
          }
        }
      } else {
        //未登录 跳转到登录页面
        wx.showModal({
          title: '提示',
          content: '现在去登录吗？',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/mime/mime',
              })
            } else if (res.cancel) {
              console.log("取消登录");
            }
          }
        })
      }
    } else {
      //不需要登录
      console.log("不需要登录")
      //已登录的状态 判断需要携带的参数
      if (paras != null && paras.length > 0) {
        //有参数 需要拼接参数  完成后页面跳转
        if (finalUrl.startsWith('/pages/')) {
          //需要拼接参数 小程序内部页面不要传额外参数
          console.log("有参数 小程序内跳转 " + finalUrl);
          wx.navigateTo({
            url: finalUrl,
          })
        } else {
          finalUrl = banner.linkUrl.replace("?", "&");
          //需要拼接参数 参数名称需要是固定的，比如uid fid dxfid
          var parasList = paras.split(",");
          for (var i = 0; i < parasList.length; i++) {
            if (parasList[i] == "uid") {
              finalUrl = finalUrl + "&" + parasList[i] + "=" + cxid;
            } else if (parasList[i] == "fid") {
              finalUrl = finalUrl + "&" + parasList[i] + "=" + app.globalData.fid;
            } else if (parasList[i] == "dxfid") {
              finalUrl = finalUrl + "&" + parasList[i] + "=" + app.globalData.site.schoolid;
            } else if (parasList[i] == "enc") {
              //入馆预约定制
              var md5str = '[fid=' + app.globalData.fid + '][uid=' + wx.getStorageSync('cxid') + '][)lEeoJVv0Y7T5e*=SC]';
              var _enc = md5.md5(md5str);
              finalUrl = finalUrl + "&" + parasList[i] + "=" + _enc;
            }
          }
          console.log("有参数跳转 " + finalUrl);
          wx.navigateTo({
            url: '/pages/link/link?url=' + finalUrl + '&name=' + name,
          })
        }

      } else {
        //没有额外参数 直接跳转  需要判断是内嵌还是小程序私有页面
        if (finalUrl.startsWith('/pages/')) {
          console.log("无参数 小程序内跳转 " + finalUrl);
          wx.navigateTo({
            url: finalUrl,
          })
        } else {
          if (finalUrl.indexOf("?") > -1) {
            finalUrl = finalUrl + "&uid=" + cxid + "&fid=" + app.globalData.fid + "&dxfid=" + app.globalData.site.schoolid;
          } else {
            finalUrl = finalUrl + "?uid=" + cxid + "&fid=" + app.globalData.fid + "&dxfid=" + app.globalData.site.schoolid;
          }
          wx.navigateTo({
            url: '/pages/link/link?url=' + encodeURIComponent(finalUrl + '&name=' + name)
          })
        }
      }

    }
  },


  openLocation: function (e) {
    var site = app.globalData.site;
    wx.openLocation({
      latitude: Number(site.latitude),
      longitude: Number(site.longitude),
      name: site.name,
      scale: 10,
      fail: function (res) {
        console.log(res);
        wx.showToast({
          title: '定位信息异常！',
          icon: 'none'
        })
      }
    })
  },





  ssbmHandle: function () {
    var fid = app.globalData.fid;
    var uid = wx.getStorageSync('cxid');
    // if(fid == "117890" || fid == ""){
    //增加判断登录
    if (uid && uid > 0) {
      wx.navigateTo({
        url: '/pages/activityList/list',
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '现在去登录吗？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {

          }
        }
      })
    }
  },



  // 选择单位



  /**
   * 图书馆确定按钮
   */
  bindsure: function () {
    this.setData({
      popshow: false,
      currentLibraryId: null
    })
    //TODO 需要将对应图书馆的信息写入app.js 然后加载页面

    let site = this.data.currentSite;

    wx.setStorageSync('site', site);
    app.globalData.fid = site.fid;

    wx.setStorageSync('fid', site.fid);
    app.globalData.fidEnc = site.fidEnc;
    app.globalData.province = site.province;
    app.globalData.city = site.city;
    app.globalData.district = site.district;
    app.globalData.allowLocation = true;
    app.globalData.site = site;
    console.log("app.globalData.site")
    console.log(app.globalData.site)
    this.getBanner(1)
    this.getBanner(2)
    this.getBanner(3)
    this.getMuseumCode(site.fid)
  },
  //根据fid获取museumCode
  getMuseumCode(fid) {
    wx.request({
      url: app.globalData.baseUrl + 'admin/front/group/code',
      method: 'get',
      data: {
        fid: fid
      },
      success: function (res) {
        console.log(222222, res)
        if (res.statusCode == 200) {
          let data = res.data
          if (data && data.status == 200) {
            app.globalData.museumCode = data.data;
          } else {
            console.log("获取museumCode失败");
          }
        } else {
          console.log("获取museumCode失败");
        }
      },
      fail: function () {
        console.log("获取museumCode失败");
      }
    })
  },
  /**
   * 关闭弹窗
   */
  closeWrapper: function () {
    this.setData({
      popshow: false
    })
  },
  /**
   * 图书馆列表分页
   * 
   */
  addrscrolltolower: function () {

    if (this.data.listType == "local") {
      this.getCities()
    } else {
      this.searchLibrary(this.data.sw)
    }
  },
  /**
   * 重新定位
   */
  refreshAddr: function () {
    this.setData({
      currentLibraryId: null,
      pageNumber: 1,
      libraryList: [],
      locationShow: false,
      listType: 'local'
    })
    this.getUserLocation();
  },
  /**
   * 选择图书馆
   */
  checkCurrentLibrary: function (e) {
    var currentId = e.currentTarget.dataset.id;
    this.setData({
      currentSite: this.data.libraryList[currentId]
    })

  },
  inputEventListener: function (e) {
    this.setData({
      sw: e.detail
    })
  },
  onClickIcon: function (e) {

    this.setData({
      libraryList: [],
      pageNumber: 1,
      listType: 'search'
    })
    let sw = this.data.sw.value;
    if (sw != "" && sw != undefined) {
      this.searchSites(sw)
    }
  },
  onSearchLibrary: function (e) {
    let vm = this;
    vm.setData({
      listType: 'search',
      sw: e.detail,
      libraryList: [],
      pageNumber: 1
    })
    // if (e.detail != "" && e.detail != undefined) {
    vm.searchSites(vm.data.sw)
    // }
  },

  searchLibrary: function (sw) {
    let vm = this;
    vm.setData({
      listType: 'search',
      sw: sw
    })
    vm.searchSites(sw)
  },

  /**
   * 搜索站点
   */
  searchSites: function (name) {
    let vm = this;
    var encarr = []
    if (name == '') {
      encarr = [{
        pageSize: 10
      }, {
        pageNumber: vm.data.pageNumber
      }, {
        order: 1
      }, {
        libraryType: 3
      }]
    } else {
      encarr = [{
        pageSize: 10
      }, {
        pageNumber: vm.data.pageNumber
      }, {
        sw: name
      }, {
        order: 1
      }, {
        libraryType: 3
      }]
    }
    var enc = app.generateEnc(encarr)
    wx.request({
      url: 'https://manageshequ3.chaoxing.com/api/searchsite',
      data: {
        sw: name,
        pageSize: 10,
        pageNumber: vm.data.pageNumber,
        order: 1,
        libraryType: 3, //类型 1图书馆 add by carlos at 2020-05-20
        sid: 1, //预留字段 add by carlos at 2020-05-20
        enc:enc
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (res.data.data.total == 0) {
            let site = {
              fid: 132334,
              id: 1,
              fidEnc: 'd6517f679046dcf3',
              name: '博以览物',
              custom: '{"AccessID": "","key": ""}'
            }
            res.data.data.records[res.data.data.records.length] = site
          }
          var records = res.data.data.records
          records.forEach(t => {
            try {
              JSON.parse(t.custom)
            } catch (error) {
              t.custom = t.custom!='' ? app.decrypt(t.custom) : t.custom
              t.appid = t.appid!='' ? app.decrypt(t.appid) : t.appid
              t.fidEnc = t.fidEnc!='' ? app.decrypt(t.fidEnc) : t.fidEnc
              t.fidEncH5 = t.fidEncH5!='' ? app.decrypt(t.fidEncH5) : t.fidEncH5
              t.secret = t.secret!='' ? app.decrypt(t.secret) : t.secret
            }
          })
          vm.setData({
            libraryList: vm.data.libraryList.concat(records),
            pageNumber: vm.data.pageNumber + 1
          })
        }
      },
      fail: function () {
        console.log("获取当前城市下属单位失败")
      }
    })
  },

  /**
   * 校验fidEnc
   */
  checkFidEnc: function (fid) {
    var that = this;
    var encarr = [{
      fid: fid
    }]
    var enc = app.generateEnc(encarr)
    wx.request({
      url: 'https://manageshequ3.chaoxing.com/api/getsitebyfid?fid=' + fid + '&enc=' + enc,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.code == 200) {
          let site = res.data.data;
          try {
            JSON.parse(site.custom)
          } catch (error) {
            site.custom = site.custom != '' ? app.decrypt(site.custom) : site.custom
            site.appid = site.appid!=''?app.decrypt(site.appid):site.appid
            site.fidEnc = site.fidEnc!=''?app.decrypt(site.fidEnc):site.fidEnc
            site.fidEncH5 = site.fidEncH5!=''?app.decrypt(site.fidEncH5):site.fidEncH5
            site.secret = site.secret!=''?app.decrypt(site.secret):site.secret
          }
          that.setData({
            currentSite: site
          })
          app.globalData.site = site;
        } else {
          console.log("enc校验未通过")
        }
      },
      fail: function () {
        console.log("校验服务器出错")
      }
    })
  },

  selectSite: function (e) {
    let index = e.currentTarget.dataset.index;
    let site = this.data.localCities[index];
    wx.setStorageSync('site', site);
    app.globalData.fid = site.fid;
    app.globalData.fidEnc = site.fidEnc;
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  getUserLocation: function (e) {
    var vm = this;

    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
                console.log("拒绝授权地理位置 展示默认列表")

                //TODO 拒绝授权地理位置，使用默认的app.js数据加载首页资源
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();

        } else {
          //调用wx.getLocation的API
          vm.getLocation();

        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.loadCity(latitude, longitude)
      },
      fail: function (res) {
        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {
              console.log("用户拒绝授权")
            } else {
              //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
              wx.showModal({
                title: '',
                content: '请在系统设置中打开定位服务',
                confirmText: '确定',
                success: function (res) {}
              })
            }
          }
        })

      }
    })
  },

  //获取当前城市所属单位
  getCities: function () {
    let vm = this;
    var encarr = [{
      pageSize: 6
    }, {
      pageNumber: this.data.pageNumber
    }, {
      city: this.data.city
    }, {
      libraryType: 3
    }]
    var enc = app.generateEnc(encarr)
    wx.request({
      url: 'https://manageshequ3.chaoxing.com/api/citysites',
      data: {
        city: this.data.city,
        pageSize: 6,
        pageNumber: this.data.pageNumber,
        libraryType: 3, //类型 1图书馆 add by carlos at 2020-05-20
        sid: 1,//预留字段 add by carlos at 2020-05-20
        enc:enc
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (res.data.data.total == 0) {
            let site = {
              fid: 132334,
              id: 1,
              fidEnc: 'd6517f679046dcf3',
              name: '博以览物',
              custom: '{"AccessID": "","key": ""}'
            }
            res.data.data.records[res.data.data.records.length] = site
          }
          var records = res.data.data.records
          records.forEach(t => {
            try {
              JSON.parse(t.custom)
            } catch (error) {
              t.custom = t.custom!='' ? app.decrypt(t.custom) : t.custom
              t.appid = t.appid!='' ? app.decrypt(t.appid) : t.appid
              t.fidEnc = t.fidEnc!='' ? app.decrypt(t.fidEnc) : t.fidEnc
              t.fidEncH5 = t.fidEncH5!='' ? app.decrypt(t.fidEncH5) : t.fidEncH5
              t.secret = t.secret!='' ? app.decrypt(t.secret) : t.secret
            }
          })
          vm.setData({
            libraryList: vm.data.libraryList.concat(records),
            pageNumber: vm.data.pageNumber + 1,
            locationShow: true
          })
        }
      },
      fail: function () {
        console.log("获取当前城市下属单位失败")
        vm.setData({
          locationShow: true
        })
      }
    })
  },

  //把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置，天气情况等信息
  loadCity: function (latitude, longitude) {

    var vm = this;
    var myAmapFun = new amapFile.AMapWX({
      key: 'fe45065f41c8ace6763bd2ca631ddad7'
    });
    myAmapFun.getRegeo({
      location: '' + longitude + ',' + latitude + '', //location的格式为'经度,纬度'
      success: function (res) {

        let address = res[0].regeocodeData.addressComponent;
        // console.log("当前城市"+JSON.stringify(address))
        let province = address.province;
        let district = address.district;
        let city = address.city;
        if (city.length == 0) {
          city = province
        }
        app.globalData.province = province;
        app.globalData.city = city;
        app.globalData.district = district;
        vm.setData({
          province: province,
          city: city,
          district: district,
          popshow: true
        })

        vm.getCities();
      },
      fail: function (info) {}
    });
  },

  scanCode: function () {
    var _this = this;
    var uid = wx.getStorageSync('cxid');
    if (uid && uid > 0) {
      // wx.scanCode({
      //   success: (res) => {
      //     _this.enterLib(res.result, uid);
      //   }
      // })
      wx.scanCode({
        success: (res) => {
          console.log(res);
          var result = decodeURIComponent(res.result);
          console.log("test: " + result);
          _this.enterLib(result, uid);
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '现在去登录吗？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
            console.log("取消登录");
          }
        }
      })
    }
  },

  enterLib: function (fid, uid) {
    //进行登录入馆，成功->跳转， 失败->提示
    var currentFid = app.globalData.fid;
    wx.request({
      url: 'https://entry-reg.libsp.com/inlib/user/login',
      method: 'POST',
      data: {
        "fid": fid,
        "uid": uid
      },
      success: function (res) {
        if (res.data.success) {
          // if (res.data.data.status) {

          var md5str = '[fid=' + currentFid + '][uid=' + uid + '][)lEeoJVv0Y7T5e*=SC]';
          var _enc = md5.md5(md5str)
          // var _url = 'https://entry-reg.libsp.com/&fid=' + currentFid + '&uid=' + uid + '&enc=' + _enc;
          // wx.navigateTo({
          //   url: '/pages/link/link?url=' + _url,
          // })
          var _url = 'https://entry-reg.libsp.com' + res.data.data.url.replace(/\s+/g, '') + '&fid=' + currentFid + '&uid=' + uid + '&enc=' + _enc;
          wx.navigateTo({
            url: '/pages/link/link?url=' + _url,
          })
          // } else {
          //   //入馆失败，提示失败信息
          //   setTimeout(function () {
          //     wx.showToast({
          //       title: res.data.data.message,
          //       icon: 'none',
          //       duration: 2000
          //     })
          //   }, 1000)
          // }
        } else {
          //wx.hideLoading();
          setTimeout(function () {
            wx.showToast({
              title: "扫码入馆失败",
              icon: 'none',
              duration: 2000
            })
          }, 1000)
        }
      },
      error: function () {
        // wx.hideLoading()
        setTimeout(function () {
          wx.showToast({
            title: "扫码入馆失败",
            icon: 'none',
            duration: 2000
          })
        }, 1000)
      }
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      currentSite: app.globalData.site
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})